
import {cacheTools} from 'nc-lightapp-front';
import CommonAction from '../../../public/actions/employing/common';

import {getQueryCondition} from '../../../../hrpub/common/utils/utils';

export default class TableAction extends CommonAction {
    constructor(comp) {
        super();
        this.comp = comp;
        this.action = comp.action;
    }

    // 选择一行
    selectRow = (...args) => {
        const {props} = this.comp;
        const {dispatch, editTable} = props;

        let selected = editTable.getAllRows('list').length === editTable.getCheckedRows('list').length

        this.update({
            tableSelectAll: selected
        });
    }

    // 请求表格数据
    postMainTableData = async (postData) => {
        const {
            props: {
                dispatch
            }
        } = this.comp;

        try {
            let res = await dispatch({
                type: 'emp/getMainTableData',
                payload: {
                    postData: postData
                }
            });
            return res;
        }
        catch(e) {
            console.error(`postMainTableData: ${e}`);
        }
        return {
            success: false
        };
    }

    // 获取主表数据
    getMainTableData = async ({
        conditions, 
        pageInfo, 
        pk_org, 
        orderBeginTime, 
        billstate, 
        orderEndTime, 
        oid, 
        time,
        pk_trnstype,
        hasSearched
    } = {}) => {
        const {props} = this.comp;
        const {search, emp, meta, dispatch, editTable} = props;

        // 保证调用方式有两种，传参，如果没有传惨就从store拿
        !conditions && (conditions = getQueryCondition(props, 'query'));
        !pageInfo && (pageInfo = emp.pageInfo);
        !pk_org && (pk_org = emp.orgValue ? emp.orgValue.refpk : '');
        !orderBeginTime && (orderBeginTime = emp.orderBeginTime);
        !billstate && (billstate = emp.orderStatus);
        !orderEndTime && (orderEndTime = emp.orderEndTime);
        !oid && (oid = meta.getMeta()['query'].oid);
        !time && (time = emp.orderTimeRange);
        !pk_trnstype && (pk_trnstype = emp.leaveType ? emp.leaveType.refpk : '');
        pk_trnstype === 'empty' && (pk_trnstype = '');
        hasSearched === undefined && (hasSearched = emp.hasSearched);

        if(hasSearched === false) {
            // return;
        }

        let postData = {
            queryAreaCode: 'querybill',
            querytype: 'true',
            querycondition: {
                logic: 'and',
                conditions: []
            },
            ...conditions, 
            pageInfo: {
                ...pageInfo,
                pageIndex: pageInfo.pageIndex
            }, 
            pk_org, 
            beginTime: orderBeginTime, 
            billstate: billstate.join(','), 
            endTime: orderEndTime, 
            oid, 
            time,
            pk_trnstype
        };

        // 如果是用户自定义时间范围则时间范围字段置空
        postData.time === 'custom' && (postData.time = '');
        
        let res = await this.postMainTableData(postData);

        if(res.success) {
            let allpks = [];
            let tableData = {rows: []};
            
            if(res.data && res.data.data && res.data.data.list) {
                let pageInfo = this.deepCopy(res.data.data.list.pageInfo);

                this.update({
                    pageInfo: {
                        ...pageInfo,
                        pageIndex: parseInt(pageInfo.pageIndex)
                    },
                    tableSelectAll: false,
                    isApprove: res.data.isApprove
                });
                tableData = res.data.data.list;
                allpks = res.data.data.list.rows.map((item) => {
                    return item.values['pk_hi_stapply'].value
                });
            }
            cacheTools.set('allpks', allpks);

            editTable.setTableData('list', tableData, false);
            editTable.showColByKey('list', 'operation')
        }
    }
    getWidgetTableData = async ({
        value,
        pageInfo, 
    } = {}) => {
        const {props} = this.comp;
        const {search, emp, meta, dispatch, editTable} = props;

        // 保证调用方式有两种，传参，如果没有传惨就从store拿
        !pageInfo && (pageInfo = emp.pageInfo);

        let postData = {
            widgetCode:"6008C080",
            appCode:"60092060",
            pageCode:"60092060nccloud",
            areaCode:"list",
            pageInfo: {
				pageSize: parseInt(pageInfo.pageSize),
				total: parseInt(pageInfo.total),
				totalPage:parseInt(pageInfo.totalPage),
				pageIndex:  parseInt(pageInfo.pageIndex),
			},
        };
        try {
            let res = await dispatch({
                type: 'emp/getWidgetTableData',
                payload: {
                    postData: postData
                }
            });
            if(res.success) {
                let allpks = [];
                let tableData = {rows: []};
                
                if(res.data && res.data.list) {
                    let pageInfo = this.deepCopy(res.data.list.pageInfo);
    
                    this.update({
                        pageInfo: {
                            ...pageInfo,
                            pageIndex: parseInt(pageInfo.pageIndex)
                        },
                        tableSelectAll: false
                    });
                    tableData = res.data.list;
                    allpks = res.data.list.rows.map((item) => {
                        return item.values['pk_hi_stapply'].value
                    });
                }
                cacheTools.set('allpks', allpks);
                editTable.setTableData('list', tableData, false);
                editTable.hideColByKey('list', 'operation')
            }
        } catch (e) {

        } 
    }
    // 当用户点击了全部选择按钮
    selectAll = (props, tableId, status) => {
        this.update({
            tableSelectAll: status
        });
    }

    didAllInstance = () => {
        
        this.buttonMap = {
            // 删除
            'ta_delete':  this.action.rowAct.deleteRows,
            // 修改
            'ta_edit': this.action.rowAct.editOnes,
            // 复制
            'copy': this.action.rowAct.copyOnes,
            // 附件管理
            'file_manager': this.fileManager,
            // 查看审批详情
            'approveinfo': this.action.rowAct.previewApproveInfo
        };
    }

    // 行上的附件管理
    fileManager = (...args) => {
        this.pubSub.publish('fileManager', ...args);
    }

    // 行上的操作按钮点击
    rowClickHandle = (key, record, index) => {
        let selectedRows = [record];

        console.log(key, record);

        this.buttonMap[key](selectedRows);
    }

    // 主页面主表格行双击事件
    doubleClick = (record, index, fProps, e) => {
        const {action} = this.comp;

        action.formAct.toBrowsePage([record]);
    }
}